﻿using SuperMap.Data;
using SuperMap.Realspace;
using SuperMap.UI;
using System;
using System.Collections.Generic;
using System.Data;
using WeifenLuo.WinFormsUI.Docking;
using Ycjw.PipeLine.Map.Basic.Conditions;
using Ycjw.PipeLine.Map.Basic.SuperMap;


namespace Ycjw.PipeLine.Map.Tools.Conditions.Statistics
{
    public partial class GJMSStatistics : ConditionPanel
    {
        private LayerWithDataListPanel LayerWithDataListPanel;
        public GJMSStatistics() : base()
        {
            // this.SetSize(300, 200);
            this.ConditionPanelName = "管径按埋深统计";
            InitializeComponent();
        }
        private readonly string MSQFIELDNAME = "SSStart_Depth";
        public override object Do(DockPanel dockPanel = null)
        {
            DataTable dt = new DataTable
            {
                TableName = ConditionPanelName
            };
            dt.Columns.Add("系列");
            if (uiRadioButton5Segment.Checked || uiRadioButton10Segment.Checked)
            {
                dt = StatisticsBySegment(dt);
            }
            else
            {
                dt = StatisticsByAll(dt);
            }
            /*
               var geom = Scene.TrackingLayer.Get(0);
               if (geom is GeoRegion3D)
                   geom = (geom as GeoRegion3D).ConvertToRegion();
               return (dt, geom);
            */
            return dt;
        }
        private DataTable StatisticsBySegment(DataTable dt)
        {
            Geometry geom = null;
            if (Scene.TrackingLayer.Count > 0)
            {
                geom = Scene.TrackingLayer.Get(0);
                if (geom is GeoRegion3D)
                    geom = (geom as GeoRegion3D).ConvertToRegion();
            }
            List<Layer3DDataset> datasets = this.LayerWithDataListPanel.SelectLayer3DDatasets;
            var rMin = double.MaxValue;
            var rMax = double.MinValue;
            var hasNull = false;
            foreach (Layer3DDataset layer3DDataset in datasets)
            {
                var dataSetVector = layer3DDataset.Dataset as SuperMap.Data.DatasetVector;
                if (dataSetVector.FieldInfos.IndexOf(MSQFIELDNAME) < 0) continue;
                DatasetVectorEx dvEx = new DatasetVectorEx(layer3DDataset.Dataset.Name)
                {
                    DatasetVector = dataSetVector
                };
                double[] minMax = dvEx.GetMinMaxValue(MSQFIELDNAME);
                if (minMax.Length > 1)
                {
                    if (rMin > minMax[0])
                        rMin = minMax[0];
                    if (rMax < minMax[1])
                        rMax = minMax[1];
                }
                if (!hasNull && dvEx.HasNullVal(MSQFIELDNAME)) hasNull = true;
            }
            if (rMin == double.MaxValue || rMax == double.MaxValue) return null;
            var levelCount = 5;
            if (uiRadioButton5Segment.Checked) levelCount = 6;
            if (uiRadioButton10Segment.Checked) levelCount = 11;
            if (rMin == rMax) levelCount = 1;
            if (levelCount == 1)
            {
                dt.Columns.Add(rMin + string.Empty);
            }
            else
            {
                var levelStep = (rMax - rMin) / levelCount - 1;
                for (int i = 0; i < levelCount - 1; i++)
                {
                    var v1 = (rMin + (levelStep * (i + 0))).ToString("f2");
                    var v2 = (rMin + levelStep * (i + 1)).ToString("f2");
                    if (i < levelCount - 2)
                        dt.Columns.Add(v1 + "≤X＜" + v2);
                    else
                    {
                        dt.Columns.Add(v1 + "≤X≤" + v2);
                    }
                }
            }
            if (hasNull) dt.Columns.Add("未知");

            foreach (Layer3DDataset layer3DDataset in datasets)
            {
                var dataSetVector = layer3DDataset.Dataset as SuperMap.Data.DatasetVector;
                if (dataSetVector.FieldInfos.IndexOf(MSQFIELDNAME) < 0) continue;
                DatasetVectorEx dvEx = new DatasetVectorEx(layer3DDataset.Dataset.Name)
                {
                    DatasetVector = dataSetVector
                };
                var dr = dt.NewRow();
                dr[0] = layer3DDataset.Caption;
                if (levelCount == 1)
                {
                    double count = dvEx.StaticsticsLengthByMinMax(MSQFIELDNAME, rMin - 1, rMax + 1, true, geom);
                    dr[1] = count;
                }
                else
                {
                    var levelStep = (rMax - rMin) / levelCount - 1;
                    for (int i = 0; i < levelCount - 1; i++)
                    {
                        double count;
                        if (i < levelCount - 2)
                            count = dvEx.StaticsticsLengthByMinMax(MSQFIELDNAME, rMin + levelStep * (i + 0), (rMin + levelStep * (i + 1)), false, geom);
                        else
                            count = dvEx.StaticsticsLengthByMinMax(MSQFIELDNAME, rMin + levelStep * (i + 0), (rMin + levelStep * (i + 1)), true, geom);
                        dr[i + 1] = count;
                    }
                }
                if (hasNull)
                {
                    dr[dr.ItemArray.Length - 1] = dvEx.NullValCount(MSQFIELDNAME);
                }
                dt.Rows.Add(dr);
            }

            return dt;

        }
        private DataTable StatisticsByAll(DataTable dt)
        {
            if (this.uiRadioButtoncdtj.Checked)
            {
                List<Layer3DDataset> datasets = this.LayerWithDataListPanel.SelectLayer3DDatasets;
                List<Dictionary<string, double>> results = new List<Dictionary<string, double>>();
                foreach (Layer3DDataset layer3DDataset in datasets)
                {
                    var dataSetVector = layer3DDataset.Dataset as SuperMap.Data.DatasetVector;
                    if (dataSetVector.FieldInfos.IndexOf(MSQFIELDNAME) < 0) continue;
                    DatasetVectorEx dvEx = new DatasetVectorEx(layer3DDataset.Dataset.Name)
                    {
                        DatasetVector = dataSetVector
                    };
                    var result = dvEx.UniqueValLength(MSQFIELDNAME);
                    results.Add(result);
                    foreach (var key in result.Keys)
                    {
                        double.TryParse(key, out double tmpKeyDouble);
                        var tmpKey = tmpKeyDouble.ToString("f2");
                        if (!dt.Columns.Contains(tmpKey))
                            dt.Columns.Add(tmpKey);
                    }
                }
                foreach (Layer3DDataset layer3DDataset in datasets)
                {
                    var dr = dt.NewRow();
                    dr[0] = layer3DDataset.Caption;
                    dt.Rows.Add(dr);
                }
                var rowIndex = 0;
                foreach (var r in results)
                {
                    var dr = dt.Rows[rowIndex++];
                    foreach (var key in r.Keys)
                    {
                        double.TryParse(key, out double tmpKeyDouble);
                        var tmpKey = tmpKeyDouble.ToString("f2");
                        dr[tmpKey] = r[key];
                    }
                }
            }
            if (this.uiRadioButtontstj.Checked)
            {
                List<Layer3DDataset> datasets = this.LayerWithDataListPanel.SelectLayer3DDatasets;
                List<Dictionary<string, double>> results = new List<Dictionary<string, double>>();
                foreach (Layer3DDataset layer3DDataset in datasets)
                {
                    var dataSetVector = layer3DDataset.Dataset as SuperMap.Data.DatasetVector;
                    if (dataSetVector.FieldInfos.IndexOf(MSQFIELDNAME) < 0) continue;
                    DatasetVectorEx dvEx = new DatasetVectorEx(layer3DDataset.Dataset.Name)
                    {
                        DatasetVector = dataSetVector
                    };
                    var result = dvEx.UniqueValLengths(MSQFIELDNAME);
                    results.Add(result);
                    foreach (var key in result.Keys)
                    {
                        double.TryParse(key, out double tmpKeyDouble);
                        var tmpKey = tmpKeyDouble.ToString("f2");
                        if (!dt.Columns.Contains(tmpKey))
                            dt.Columns.Add(tmpKey);
                    }
                }
                foreach (Layer3DDataset layer3DDataset in datasets)
                {
                    var dr = dt.NewRow();
                    dr[0] = layer3DDataset.Caption;
                    dt.Rows.Add(dr);
                }
                var rowIndex = 0;
                foreach (var r in results)
                {
                    var dr = dt.Rows[rowIndex++];
                    foreach (var key in r.Keys)
                    {
                        double.TryParse(key, out double tmpKeyDouble);
                        var tmpKey = tmpKeyDouble.ToString("f2");
                        dr[tmpKey] = r[key];
                    }
                }
            }

            return dt;
        }
        protected override void OnLoad(EventArgs e)
        {
            LayerWithDataListPanel = new LayerWithDataListPanel()
            {
                Dock = System.Windows.Forms.DockStyle.Top
            };
            Scene scene = this.Scene;
            if (scene == null) return;
            LayerWithDataListPanel.Init(scene);

            var types = new List<DatasetType>()
            {
                DatasetType.Line,
                DatasetType.Line3D,
                DatasetType.Network,
                DatasetType.Network3D
            };
            LayerWithDataListPanel.LoadTo(types, true);
            this.uiGroupBoxtjtc.Controls.Add(LayerWithDataListPanel);
            AddSqlConditions();

            this.uiPanelLeft.Width = this.Width / 2;

            uiGroupBoxtjtc.Height = uiGroupBoxtjtc.Parent.Height / 2;
            uiGroupBoxtjfs.Height = uiGroupBoxtjfs.Parent.Height / 2;
        }
        //空间查询-------------
        private void AddSqlConditions()
        {
            Sunny.UI.UIRadioButton rb1 = new Sunny.UI.UIRadioButton()
            {
                Text = "矩形查询",
                Name = "RetacleQuery",
                Location = new System.Drawing.Point(20, 40)
            };
            Sunny.UI.UIRadioButton rb2 = new Sunny.UI.UIRadioButton()
            {
                Text = "圆形查询",
                Name = "CycleQuery",
                Location = new System.Drawing.Point(20, 68)
            };
            Sunny.UI.UIRadioButton rb3 = new Sunny.UI.UIRadioButton()
            {
                Text = "多边形查询",
                Name = "PolygonQuery",
                Location = new System.Drawing.Point(20, 96)
            };
            uiGroupBoxkjcx.Controls.Add(rb1);
            uiGroupBoxkjcx.Controls.Add(rb2);
            uiGroupBoxkjcx.Controls.Add(rb3);
            rb1.ValueChanged += ValueChanged;
            rb2.ValueChanged += ValueChanged;
            rb3.ValueChanged += ValueChanged;
            SceneControl sceneControl = this.SceneControl;
            if (sceneControl == null) return;
            sceneControl.Tracked += SceneControl_Tracked;
            sceneControl.Tracking += SceneControl_Tracking;
        }

        private void SceneControl_Tracking(object sender, Tracking3DEventArgs e)
        {
            if (Action3D.CreateLine != this.SceneControl.Action) return;
            var tag = "cycle_tmp";
            var index = Scene.TrackingLayer.IndexOf(tag);
            if (index > -1)
            {
                Scene.TrackingLayer.Remove(index);
            }
            GeoLine3D line3d = e.Geometry as GeoLine3D;
            if (line3d == null || line3d.Length == 0)
            {
                return;
            }
            var ps = line3d[0];
            var length = Math.Sqrt(Math.Pow((ps[0].X - ps[1].X), 2) + Math.Pow((ps[0].Y - ps[1].Y), 2));
            Point2D p2d = new Point2D(ps[0].X, ps[0].Y);
            GeoRectangle gr = new GeoRectangle(p2d, length * 2, length * 2, 0);
            GeoEllipse ge = new GeoEllipse(gr);
            var gReg = ge.ConvertToRegion(40);
            var p3ds = new Point3Ds();
            for (int i = 0; i < gReg[0].Count; i++)
            {
                p3ds.Add(new Point3D(gReg[0][i].X, gReg[0][i].Y, 0));
            }
            var gReg3d = new GeoRegion3D(p3ds)
            {
                Style3D = new GeoStyle3D()
                {
                    LineColor = System.Drawing.Color.Yellow,
                    LineWidth = 2,
                    FillBackColor = System.Drawing.Color.FromArgb(120, System.Drawing.Color.Yellow),
                    FillForeColor = System.Drawing.Color.FromArgb(120, System.Drawing.Color.Yellow),
                    AltitudeMode = AltitudeMode.ClampToGround
                }
            };
            Scene.TrackingLayer.Add(gReg3d, tag);
        }
        private void SceneControl_Tracked(object sender, Tracked3DEventArgs e)
        {
            var geom = e.Geometry;
            if (geom == null) return;
            if (geom.Type == SuperMap.Data.GeometryType.GeoLine3D)
            {

            }
            else
            {
                geom.Style3D = new GeoStyle3D()
                {
                    LineColor = System.Drawing.Color.Yellow,
                    LineWidth = 2,
                    FillBackColor = System.Drawing.Color.FromArgb(120, System.Drawing.Color.Yellow),
                    FillForeColor = System.Drawing.Color.FromArgb(120, System.Drawing.Color.Yellow),
                    AltitudeMode = AltitudeMode.ClampToGround
                };
                Scene.TrackingLayer.Add(geom, string.Empty);
            }
        }

        public override bool ConditionValid()
        {
            if (this.LayerWithDataListPanel.SelectLayer3DDatasets.Count == 0)
            {
                return false;
            }

            if (LayerWithDataListPanel == null || LayerWithDataListPanel.SelectLayer3DDatasets == null)
            {
                Sunny.UI.UIMessageTip.ShowError("未获取到选中图层");
                IsConditionValid = false;
                return false;
            }
            foreach (var layer in LayerWithDataListPanel.SelectLayer3DDatasets)
            {
                if (!(layer.Dataset is DatasetVector)) return false;
            }
            return base.ConditionValid();


        }

        private void ValueChanged(object sender, bool value)
        {
            SceneControl sceneControl = this.SceneControl;
            if (sceneControl == null) return;
            Scene.TrackingLayer.Clear();
            Sunny.UI.UIRadioButton btn = sender as Sunny.UI.UIRadioButton;
            if (!btn.Checked) return;
            if (btn.Name == "RetacleQuery")
            {
                sceneControl.Action = Action3D.CreateRectangle;
            }
            else if (btn.Name == "CycleQuery")
            {
                sceneControl.Action = Action3D.CreateLine;
            }
            else if (btn.Name == "PolygonQuery")
            {
                sceneControl.Action = Action3D.CreatePolygon;
            }
        }

        public override void AfterClose()
        {
            SceneControl sceneControl = this.SceneControl;
            if (sceneControl == null) return;
            sceneControl.Action = Action3D.Pan;
            sceneControl.Tracked -= SceneControl_Tracked;
            sceneControl.Tracking -= SceneControl_Tracking;
            Scene.TrackingLayer.Clear();
        }


    }
}
